package com.unicorn.util.common;

import com.unicorn.base.VinaceConfig;
import com.unicorn.vo.FileVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by user on 2016/12/3.
 */
@Component
public class FileComponent extends BaseComponent {


    private static Logger logger = LoggerFactory.getLogger(FileComponent.class);


    private String rootPath = VinaceConfig.ONLINE_FILE_SYSTEM_ROOT;
    private String currentPath = "./";

    public List<File> listFiles(String filePath) {
        if (filePath == null) {
            filePath = rootPath;
        }
        if ("".equals(filePath)) {
            filePath = currentPath;
        }
        File baseDir = new File(filePath);
        File[] files = baseDir.listFiles();
        if (files == null) {
            return new ArrayList<File>();
        }
        return Arrays.asList(baseDir.listFiles());
    }

    public File createFile(FileVO fileVO) {
        File file = new File(fileVO.getFileFullPath());

        if (file.exists()) {
            fileVO.setFileName(fileVO.getFileName() + System.currentTimeMillis());
        }
        file = new File(fileVO.getFileFullPath());
        file.setWritable(true);
        file.setReadable(true);
        try {
            boolean sign = file.createNewFile();
            if (!sign) {
                logger.error("创建文件" + file.getName() + "失败");
                throw new RuntimeException("创建文件" + file.getName() + "失败 at" + System.currentTimeMillis());

            }
        } catch (IOException e) {
            logger.error("创建文件" + file.getName() + "失败" + e.getStackTrace());
        }
        return file;
    }

    public File createDirectory(FileVO fileVO) {
        File file = new File(fileVO.getFileFullPath());

        if (file.exists()) {
            fileVO.setFileName(fileVO.getFileName() + System.currentTimeMillis());
        }
        file = new File(fileVO.getFileFullPath());
        file.setWritable(true);
        file.setReadable(true);
        boolean sign = file.mkdirs();
        if (!sign) {
            logger.error("创建目录" + file.getName() + "失败");
            throw new RuntimeException("创建目录" + file.getName() + "失败 at" + System.currentTimeMillis());
        }

        return file;
    }
}
